package com.ruoyi.web.controller.datastatistics;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.datastatistics.domain.TerminalsDayfreezeDb;
import com.ruoyi.datastatistics.model.TerminalsDayRangeFreezeDbResultModel;
import com.ruoyi.datastatistics.service.ITerminalsDayfreezeDbService;
import com.ruoyi.datastatistics.vo.DbHourUsageVO;
import com.ruoyi.datastatistics.vo.MiniFlowComparisonVO;
import com.ruoyi.datastatistics.vo.PressureWatchVO;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 大表日用量数据Controller
 *
 * @author ruoyi
 * @date 2023-09-07
 */
@RestController
@RequestMapping("/datastatistics/terminalsdayfreezedb")
public class TerminalsDayfreezeDbController extends BaseController {
    @Autowired
    private ITerminalsDayfreezeDbService terminalsDayfreezeDbService;

    /**
     * 查询大表日用量数据列表
     */
    @PreAuthorize("@ss.hasPermi('datastatistics:terminal:list')")
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam Map<String, Object> paramMap) {
        System.out.println(paramMap);
        startPage();
        List<TerminalsDayfreezeDb> list = terminalsDayfreezeDbService.getTerminalsDayfreezeDbList(paramMap);
        return getDataTable(list);
    }

    /**
     * 查询小冻结数据（设备维度）列表
     */
    @PreAuthorize("@ss.hasAnyPermi('datastatistics:terminalsfreezexb:list,basedata:terminalsdb:list')")
    @GetMapping("/listThirtyDaysFlow")
    public AjaxResult listThirtyDaysFlow(TerminalsDayfreezeDb terminalsDayfreezeDb) {
        List<TerminalsDayfreezeDb> list = terminalsDayfreezeDbService.listThirtyDaysFlow(terminalsDayfreezeDb);
        if (CollUtil.isNotEmpty(list)) {
            list.sort(Comparator.comparing(TerminalsDayfreezeDb::getGetTimeN));
        }
        return success(list);
    }

    @PreAuthorize("@ss.hasPermi('datastatistics:terminal:list')")
    @GetMapping("/listRange")
    public TableDataInfo listRange(@RequestParam Map<String, Object> paramMap) {
        System.out.println(paramMap);
        startPage();
        List<TerminalsDayRangeFreezeDbResultModel> list = terminalsDayfreezeDbService.getTerminalsDayRangeFreezeDbList(paramMap);
        return getDataTable(list);
    }

    /**
     * 导出大表日用量数据列表
     */
    @PreAuthorize("@ss.hasPermi('datastatistics:terminal:list')")
    @Log(title = "大表日用量数据", businessType = BusinessType.EXPORT)
    @PostMapping("/exportDay")
    public void exportDay(HttpServletResponse response, @RequestParam Map<String, Object> paramMap) {
        List<TerminalsDayfreezeDb> list = terminalsDayfreezeDbService.getTerminalsDayfreezeDbList(paramMap);
        ExcelUtil<TerminalsDayfreezeDb> util = new ExcelUtil<>(TerminalsDayfreezeDb.class);
        util.exportExcel(response, list, "大表日用量数据数据");
    }

    /**
     * 导出大表日用量数据列表
     */
    @PreAuthorize("@ss.hasPermi('datastatistics:terminal:list')")
    @Log(title = "大表日用量数据", businessType = BusinessType.EXPORT)
    @PostMapping("/exportRange")
    public void exportRange(HttpServletResponse response, @RequestParam Map<String, Object> paramMap) {
        List<TerminalsDayRangeFreezeDbResultModel> list = terminalsDayfreezeDbService.getTerminalsDayRangeFreezeDbList(paramMap);
        ExcelUtil<TerminalsDayRangeFreezeDbResultModel> util = new ExcelUtil<>(TerminalsDayRangeFreezeDbResultModel.class);
        util.exportExcel(response, list, "大表日用量数据数据");
    }

    /**
     * 获取大表日用量数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('datastatistics:terminalsdayfreezedb:query')")
    @GetMapping(value = "/{Id}")
    public AjaxResult getInfo(@PathVariable("Id") Long Id) {
        return success(terminalsDayfreezeDbService.selectTerminalsDayfreezeDbById(Id));
    }

    /**
     * 新增大表日用量数据
     */
    @PreAuthorize("@ss.hasPermi('datastatistics:terminalsdayfreezedb:add')")
    @Log(title = "大表日用量数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TerminalsDayfreezeDb terminalsDayfreezeDb) {
        return toAjax(terminalsDayfreezeDbService.insertTerminalsDayfreezeDb(terminalsDayfreezeDb));
    }

    /**
     * 修改大表日用量数据
     */
    @PreAuthorize("@ss.hasPermi('datastatistics:terminalsdayfreezedb:edit')")
    @Log(title = "大表日用量数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TerminalsDayfreezeDb terminalsDayfreezeDb) {
        return toAjax(terminalsDayfreezeDbService.updateTerminalsDayfreezeDb(terminalsDayfreezeDb));
    }

    /**
     * 删除大表日用量数据
     */
    @PreAuthorize("@ss.hasPermi('datastatistics:terminalsdayfreezedb:remove')")
    @Log(title = "大表日用量数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{Ids}")
    public AjaxResult remove(@PathVariable Long[] Ids) {
        return toAjax(terminalsDayfreezeDbService.deleteTerminalsDayfreezeDbByIds(Ids));
    }

    /**
     * 大表综合报表日数据
     *
     * @param terminalsDayfreezeDb 查询条件
     * @return TableDataInfo
     */
    @GetMapping("/getReportByDay")
    public TableDataInfo getReportByDay(TerminalsDayfreezeDb terminalsDayfreezeDb) {
        SysUser user = getLoginUser().getUser();
        if (user.getSystemFlag() != 1 && user.getSystemFlag() != 0) {
            Long userId = user.getUserId();
            terminalsDayfreezeDb.getParams().put("sysUserId", userId);
        }
        List<TerminalsDayfreezeDb> list = terminalsDayfreezeDbService.reportListByDay(terminalsDayfreezeDb);
        return getDataTable(list);
    }

    /**
     * 大表综合报表日数据导出
     *
     * @param terminalsDayfreezeDb 查询条件
     */
    @PostMapping("/exportReportByDay")
    public void exportReportByDay(TerminalsDayfreezeDb terminalsDayfreezeDb, HttpServletResponse response) {
        SysUser user = getLoginUser().getUser();
        if (user.getSystemFlag() != 1 && user.getSystemFlag() != 0) {
            Long userId = user.getUserId();
            terminalsDayfreezeDb.getParams().put("sysUserId", userId);
        }
        if (!org.apache.commons.lang3.StringUtils.isAllBlank(terminalsDayfreezeDb.getStartTime(), terminalsDayfreezeDb.getEndTime())){
            terminalsDayfreezeDb.setGetTimeN(null);
        }
        terminalsDayfreezeDb.getParams().put("export", true);
        List<TerminalsDayfreezeDb> list = terminalsDayfreezeDbService.reportListByDay(terminalsDayfreezeDb);
        ExcelUtil<TerminalsDayfreezeDb> util = new ExcelUtil<>(TerminalsDayfreezeDb.class);
        util.exportExcel(response, list, "综合报表日数据");
    }

    /**
     * 大表时用量
     *
     * @param usageVO usageVO
     * @return TableDataInfo
     */
    @GetMapping("/getHourUsages")
    public TableDataInfo getHourUsages(DbHourUsageVO usageVO, HttpServletRequest request) {
        if (StringUtils.isBlank(usageVO.getLocationNb())) {
            throw new ServiceException("请先选择终端！");
        }
        if (StringUtils.isAnyBlank(usageVO.getBeginDate(), usageVO.getEndDate())) {
            throw new ServiceException("起止时间不能为空！");
        }
        int pageSize = NumberUtils.toInt(request.getParameter("pageSize"), 10);
        int pageNum = NumberUtils.toInt(request.getParameter("pageNum"), 1);
        usageVO.setPageNumber(pageNum);
        usageVO.setPageLength(pageSize);
        usageVO.setOffset((pageNum - 1) * pageSize);
        Long count = terminalsDayfreezeDbService.countHourUsages(usageVO);
        List<DbHourUsageVO> list = new ArrayList<>(0);
        if (count > 0){
            list = terminalsDayfreezeDbService.hourUsages(usageVO);
        }
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setRows(list);
        tableDataInfo.setTotal(count);
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        return tableDataInfo;
    }

    /**
     * 导出大表时用量
     */
    @Log(title = "大表时用量", businessType = BusinessType.EXPORT)
    @PostMapping("/exportHourUsages")
    public void exportHourUsages(DbHourUsageVO usageVO, HttpServletResponse response ) {
        List<DbHourUsageVO> list = terminalsDayfreezeDbService.hourUsages(usageVO);
        ExcelUtil<DbHourUsageVO> util = new ExcelUtil<>(DbHourUsageVO.class);
        util.exportExcel(response, list, "大表时用量数据");
    }


    /**
     * 夜间小流对比
     *
     * @param miniFlowComparisonVO miniFlowComparisonVO
     * @return AjaxResult
     */
    @GetMapping("/getMiniFlowComparison")
    public AjaxResult getMiniFlowComparison(MiniFlowComparisonVO miniFlowComparisonVO) {
        if (StringUtils.isBlank(miniFlowComparisonVO.getLocationNb())) {
            return AjaxResult.error("请先选择终端！");
        }
        if (StringUtils.isAnyBlank(miniFlowComparisonVO.getBeginDate(), miniFlowComparisonVO.getEndDate())) {
            return AjaxResult.error("起止时间不能为空！");
        }
        List<MiniFlowComparisonVO> list = terminalsDayfreezeDbService.getMiniFlowComparisonList(miniFlowComparisonVO);
        //根据日期分组
        Map<String,List<MiniFlowComparisonVO>> map = new LinkedHashMap<>(list.size());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (MiniFlowComparisonVO vo:list){
            if (vo.getDate() == null){
                continue;
            }
            map.putIfAbsent(format.format(vo.getDate()),new ArrayList<>());
            map.get(format.format(vo.getDate())).add(vo);
        }
        return AjaxResult.success(map.values());
    }

    /**
     * 压力监测数据列表
     *
     * @param pressureWatchVO pressureWatchVO
     * @return TableDataInfo
     */
    @GetMapping("/getPressureWatchList")
    public TableDataInfo getPressureWatchList(PressureWatchVO pressureWatchVO) {
        SysUser user = getLoginUser().getUser();
        if (user.getSystemFlag() != 1 && user.getSystemFlag() != 0) {
            Long userId = user.getUserId();
            pressureWatchVO.setSysUseId(userId);
        }
        List<PressureWatchVO> watchVOList = terminalsDayfreezeDbService.getPressureWatchList(pressureWatchVO);
        return getDataTable(watchVOList);
    }
}
